/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package extensions;

import common.Application;
import common.EntityPresentation;
import common.ParamStorage;
import common.SortingStyle;
import dao.Entity;
import dao.EntityDAO;
import database.DatabaseException;
import formatters.Formatter;
import formatters.ViewFormatter;
import html.InputType;
import html.XHtmlFormatter;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import localization.Localization;
import presentation.PresentationElement;
import strategies.Strategy;
import strategies.WebContext;
import templates.PresentationTemplate;
import templates.PropertyTemplate;

/**
 *
 * @author Alejandro
 */
public class SearchEmployeeStrategy implements Strategy {

    @Override
    public void execute(WebContext ctx) {
        XHtmlFormatter provider = ctx.getWebFormatter();
        ParamStorage storage = ctx.getParamStorage();
        //provider.startDiv("", "operationResult");
        //provider.echo(this.getClass().getName());
        //provider.endDiv();
        boolean queryValid = storage.hasParam("search_input") && !storage.getParam("search_input").isEmpty();
        String query = queryValid ? storage.getParam("search_input") : "";

        provider.startDiv("message");
        provider.endDiv();
        if (ctx.getUid() != 0 && queryValid) {
            try {
                provider.startDiv("", "tablePanel");
                EntityDAO dao = new EntityDAO();
                dao.bind(ctx.getUid());
                provider.startDiv("table-name");
                provider.writeH2(Localization.getString(Application.getInstance().getTemplate(ctx.getUid()).getAlias()));
                provider.endDiv();
                //container = dao.findAll();
                short nameUid = 0;
                short surnameUid = 0;
                for (PropertyTemplate pt: Application.getInstance().getTemplate(ctx.getUid()).getPropertyTemplateCollection()) {
                    if (pt.getName().equals("name"))
                        nameUid = pt.getUid();
                    if (pt.getName().equals("surname"))
                        surnameUid = pt.getUid();
                }

                Iterable<EntityPresentation> results = dao.findBy(nameUid, ".?" + query + ".?");
                Iterable<EntityPresentation> nestedResults = dao.findBy(surnameUid, ".?" + query + ".?");
                Collection<EntityPresentation> container = new LinkedList<EntityPresentation>();
                for (EntityPresentation ep: results) {
                    container.add(ep);
                }

                for (EntityPresentation ep: nestedResults) {
                    boolean contains = false;
                    for (EntityPresentation ep2: container) {
                        if (ep.getPrimaryKeyValue().equals(ep2.getPrimaryKeyValue())) {
                            contains = true;
                            break;
                        }
                    }
                    if (!contains) {
                        container.add(ep);
                    }
                }

                //
                //provider.startScript("text/javascript");
                //provider.echo(String.format("alert('%d queries executed');", EntityDAO.counter));
                //provider.endScript();
                //EntityDAO.counter = 0;
                //

                SortingStyle style = Application.getInstance().getSortingStyle(ctx.getUid());
                boolean sortClicked = storage.getSortUid() != 0;
                short sortUid = (sortClicked) ? storage.getSortUid() : style.getParam();
                if (sortUid != 0) {
                    if (style.getParam() != sortUid)
                        style.setAscending(true);
                    else if (sortClicked && (style.getParam() == sortUid))
                        style.setAscending(!style.isAscending());
                    style.setParam(sortUid);
                    Entity.sort((List<EntityPresentation>) container,sortUid);
                }

                provider.startTable();
                Formatter formatter = new ViewFormatter();
                Iterable<PresentationTemplate> header = Application.getInstance().getTemplate(ctx.getUid()).getPresentationTemplateCollection();
                provider.startTr("header");
                provider.startTh();
                provider.endTh();
                for (PresentationTemplate pt : header) {
                    provider.startTh();
                    String sId = "sort_uid_" + Short.toString(pt.getUid());
                    provider.writeInput(InputType.submit, sId, sId, "header", Localization.getString(pt.getName()));
                    if (style.getParam() == pt.getUid()) {
                        if (style.isAscending())
                            provider.putImage("view-sort-ascending.png", "sorting-style");
                        else
                            provider.putImage("view-sort-descending.png", "sorting-style");
                    }
                    provider.endTh();
                }
                provider.endTr();
                for (EntityPresentation en : container) {
                    provider.startTr();
                    provider.startTd();
                    provider.writeCheckbox("row_" + en.getPrimaryKeyValue(), "", "row_check", "checkRowSelection(); ", "checkAll(this); ", false);
                    provider.endTd();
                    Iterable<PresentationElement> elements = en.getPresentationCollection();
                    for (PresentationElement p : elements) {
                        provider.startTd();
                        provider.echo(formatter.format(p));
                        provider.endTd();
                    }
                    provider.endTr();
                }
                provider.endTable();
                provider.endDiv();
            } catch (DatabaseException ex) {
                provider.putError(String.format(Localization.getString("FailedSelect"), ex.getMessage()));
            }
        } else if (!queryValid) {
            provider.startDiv("", "operationResult");
            provider.putError(Localization.getString("EmptyQuery"));
            provider.endDiv();
        }

        provider.startScript("text/javascript");
        provider.echo("checkRowSelection(); ");
        provider.endScript();
    }

}
